package com.gf.exam.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gf.common.bean.Page;
import com.gf.exam.dao.AnswerCellDao;
import com.gf.exam.dao.AnswerDao;
import com.gf.exam.dao.ExamDao;
import com.gf.exam.model.Answer;
import com.gf.exam.model.AnswerCell;
import com.gf.exam.service.AnswerService;

@Transactional
@Service("answerService")
public class AnswerServiceImpl implements AnswerService {

	@Autowired
	private AnswerDao answerDao;

	@Autowired
	private ExamDao examDao;

	@Autowired
	private AnswerCellDao answerCellDao;

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public long save(long userId, String username, long examId, int cellNo,
			String[] answerRight, String[] mouseAction, String[] inputAction,
			String[] rt) throws RuntimeException {
		int result = 0;
		long answerId = answerDao.insert(userId, username, examId, cellNo);
		if (answerId > 0) {
			result = answerCellDao.insertBatch(cellNo, answerId, answerRight,
					mouseAction, inputAction, rt);
		}

		if (result == cellNo) {
			// 更新提交数
			examDao.updateSubmitNoByOne(examId);
			return answerId;
		}

		return 0L;
	}

	@Override
	public Answer scanById(long id) {
		return answerDao.queryById(id);
	}

	@Override
	public Page getAllAnswer(long examId, int curpage, int pageSize) {
		Page page = new Page();
		page.setCurpage(curpage);
		page.setPageSize(pageSize);
		page.setResults(answerDao.queryByExamId(examId, curpage, pageSize));
		page.setTotal(answerDao.queryNumberByExamId(examId));

		return page;
	}

	@Override
	public List<AnswerCell> getAnswerCells(long answerId) {
		return answerCellDao.queryAnswerCells(answerId);
	}

	@Override
	public int getTotalCount() {
		return answerDao.queryAllCount();
	}

	@Override
	public Map<Long, List<AnswerCell>> getAllAnsewerByExamId(long examId) {
		List<Answer> ansewers = answerDao.queryByExamId(examId);
		if (ansewers == null || ansewers.size() == 0) {
			return new HashMap<Long, List<AnswerCell>>();
		}

		List<Long> answerIds = new ArrayList<Long>();
		for (Answer answer : ansewers) {
			answerIds.add(answer.getId());
		}

		return answerCellDao.queryAnswerCells(answerIds);
	}

}
